<script setup>

import { storeToRefs } from 'pinia';
import dayjs from 'dayjs';

useHead({
    title: 'HLS: Отчет Заведующих',
})

const brigadeStore = useStReport();
// const { uslSum, labSum, countLoading } = storeToRefs(brigadeStore);
const labSum = computed(() => doc_pdr_list?.value?.reduce((acc, val) => acc + val.lab_pdzr_zav.reduce((acc, val) => acc + val.stu, 0) + val.lab_pdzr_tech.reduce((acc, val) => acc + val.stu, 0) + val.lab_dzr.reduce((acc, val) => acc + val.stu, 0), 0))
const uslSum = computed(() => doc_pdr_list?.value?.reduce((acc, val) => acc + val.usl_pdzr_zav.reduce((acc, val) => acc + val.stu, 0) + val.usl_pdzr_tech.reduce((acc, val) => acc + val.stu, 0) + val.usl_dzr.reduce((acc, val) => acc + val.stu, 0), 0))
const doc_pdr_list = ref([]);
const user = useCookie('user');
const urlHome = useUrl();
const pend = ref(false)
if (user.value == null) {
    navigateTo('/login');
}
const mpp = useCookie('mpp');
const mppLS = ref(useLocalStorage.mpp)

const year = ref(0)
const month = ref(1)
const lgot = ref(0)
const dn = ref(new Date())
const dk = ref(new Date())

const selectLgotList = ref([{
    label: 'Тип льготы',
    value: 0,
    disabled: true
}, {
    label: 'Льготные наряды',
    value: 'lgot'
}, {
    label: 'Платные наряды',
    value: 'pd'
}
])

const selectPeriodID = ref(0)

// const lgot = ref(0)
const period_disable = ref(false)
const isEnableReport = ref(false)
const isResetPage = ref(false)
const podrSelect = ref(0)

// const { data: periods } = await useFetch(`${urlHome.value}lab/period_date/`)

const { data: periods } = await useFetch(`${urlHome.value}lab/period_date_dj/`)

const { data: podrList } = await useFetch(`${urlHome.value}lab/mpp_podr_list/`, {
    query: {
        mpp: mpp.value
    }
}
)

// const sumPdzrZav = computed(() => doc_pdr_list?.value?.map((doc) => doc.) doc_pdr_list?.value?.lab_pdzr_zav?.reduce((acc, val) => acc + val.stu, 0) + doc_pdr_list?.value?.usl_pdzr_zav?.reduce((acc, val) => acc + val.stu, 0))

const submitButton = computed(() => {
    return lgot.value !== 0 && podrSelect.value !== 0 && selectPeriodID.value !== 0
})
const selectPeriod = computed(() => periods.value.find((element) => element.id == selectPeriodID.value))

async function get_nar_usl() {
    pend.value = true;
    let formData = new FormData();
    if (lgot.value == 'lgot') {
        formData.append('dn', dayjs(selectPeriod.value.dn_lg).format('YYYY-MM-DD'))
        formData.append('dk', dayjs(selectPeriod.value.dk_lg).format('YYYY-MM-DD'))
    } else if (lgot.value == 'pd') {
        formData.append('dn', dayjs(selectPeriod.value.dn_pl).format('YYYY-MM-DD'))
        formData.append('dk', dayjs(selectPeriod.value.dk_pl).format('YYYY-MM-DD'))
    }
    formData.append('year', selectPeriod.value.years)
    formData.append('month', selectPeriod.value.months)
    formData.append('lgot', lgot.value)
    formData.append('podr', podrSelect.value)
    isResetPage.value = true
    const response = await $fetch(`${urlHome.value}lab/get_stat_for_zav2/`, {
        method: 'POST',
        body: formData
    })
    if (response.ok) {
        console.log(response)
        doc_pdr_list.value = response.doc_list
        year.value = response.year
        month.value = response.month
        lgot.value = response.lgot
        dn.value = response.dn
        dk.value = response.dk
    } else {

        alert("Ошибка загрузки отчета")
    }
    pend.value = false
}

function change_lgot() {
    period_disable.value = true
}

function clear_report() {
    location.reload();
}

</script>
<style>
.list-complete-move,
.list-complete-enter-active,
.list-complete-leave-active {
    transition: all 0.5s ease;
}

.list-complete-item {
    transition: all 0.8s ease;
    display: inline-block;
    margin-right: 10px;
}

.list-complete-enter-from,
.list-complete-leave-to {
    opacity: 0;
    transform: translateY(30px);
}

.list-complete-leave-active {
    position: absolute;
}
</style>

<template>
    <div>
        {{ mppLS }}
        <div class="m-4">
            <div v-if="pend">
                <LoadFetchAnimation></LoadFetchAnimation>
            </div>
            <div class="font-bold">Итого сумма: {{ Number((labSum +
                uslSum).toFixed(2)).toLocaleString() }} руб.
            </div>
            <!-- <div lass="font-bold">Ожидают закрытия: {{ sumPdzrZav ? sumPdzrZav.toFixed(2).toLocaleString() : 0 }} руб. -->
        </div>
        <div class="font-bold">С лабораторией: {{ Number(labSum.toFixed(2)).toLocaleString() }} руб.
        </div>
        <div class="font-bold">Без лаборатории: {{ Number(uslSum.toFixed(2)).toLocaleString() }} руб.
        </div>
        <div class="mb-2 text-lg space-x-1 font-semibold text-gray-900 dark:text-white flex">
            <div class="mr-2">Период:</div>
            <USelect v-model="lgot" :options="selectLgotList" @change="change_lgot()" color="green" />
            <USelect v-model.number="podrSelect" :options="podrList" option-attribute="lpu_name"
                value-attribute="lpu_number" color="green" />
            <USelect v-model="selectPeriodID" :disabled="!period_disable" :options="periods" option-attribute="nmonth"
                value-attribute="id" color="green" />
            <div v-if="isResetPage">
                <UButton class="btn btn-sm btn-primary" @click="clear_report()" label="Очистить" />
            </div>
            <div v-else>
                <UButton label="Сформировать" class="btn btn-sm btn-primary" :disabled="!submitButton"
                    @click="get_nar_usl" />
            </div>
        </div>
        <div>*Отклоненные наряды будут возвращены врачу как открытые наряды</div>
        <!-- <div>Таким образом отклоненный наряд врач сможет снова подать в отчет на проверку.</div> -->
        <div v-auto-animate>
            <ZavDoc
                v-for="({ mpp, fio, lab_pdzr_zav, lab_pdzr_tech, lab_dzr, usl_pdzr_zav, usl_pdzr_tech, usl_dzr, }) in doc_pdr_list"
                :key="mpp" :mpp="mpp" :fio="fio" :lab_pdzr_zav="lab_pdzr_zav" :lab_pdzr_tech="lab_pdzr_tech"
                :lab_dzr="lab_dzr" :usl_pdzr_zav="usl_pdzr_zav" :usl_pdzr_tech="usl_pdzr_tech" :usl_dzr="usl_dzr"
                :dn="dn" :dk="dk" :lgot="lgot" :year="year" :month="month" :get_nar_usl="get_nar_usl">
            </ZavDoc>
        </div>
    </div>
</template>